<!--报价明细表-->
<template>
  <div class="quotation-detail">
    <div class="page-header">
      <h2>报价明细</h2>
      <div class="header-actions">
        <i class="action-icon icon-hierarchy"></i>
        <i class="action-icon icon-bell"><sup>0</sup></i>
        <i class="action-icon icon-question"></i>
        <i class="action-icon icon-user"></i>
      </div>
    </div>

    <div class="content-area">
      <div class="controls-bar">
        <div class="filters">
          <div class="filter-item">
            <label>关键词</label>
            <input type="text" placeholder="请输入报价单号/产品名称/产品编号" v-model="query.keyword">
          </div>
          <div class="filter-item">
            <label>报价时间</label>
            <input type="date" placeholder="请选择创建时间" v-model="query.date">
          </div>
        </div>
        <div class="actions">
          <button class="btn btn-search" @click="onSearch">搜索</button>
          <button class="btn btn-reset" @click="onReset">重置</button>
        </div>
      </div>

      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th><input type="checkbox" v-model="allSelected"></th>
              <th>报价单号</th>
              <th>报价时间</th>
              <th>报价产品</th>
              <th>规格</th>
              <th>分类</th>
              <th>单位</th>
              <th>数量</th>
              <th>单价</th>
              <th>单项合计金额</th>
              <th>报价人</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in details" :key="index">
                            <td><input type="checkbox" v-model="item.selected"></td>
              <td class="quote-number">{{ item.quoteNumber }}</td>
              <td>{{ item.quoteDate }}</td>
              <td class="product-name">{{ item.productName }} <span class="product-code">{{ item.productCode }}</span></td>
              <td>{{ item.spec }}</td>
              <td>{{ item.category }}</td>
              <td>{{ item.unit }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ item.unitPrice }}</td>
              <td>{{ item.lineAmount }}</td>
              <td>{{ item.salesPerson }}</td>
              <td>{{ item.remark }}</td>
            </tr>
          </tbody>
        </table>
        <div class="table-footer">
           <div class="footer-actions">
                          <input type="checkbox" id="select-all-footer" v-model="allSelected">
             <label for="select-all-footer">全选</label>
             <button class="btn btn-export">导出</button>
           </div>
           <div class="pagination">
             <button @click="changePage(page.pageNum - 1)" :disabled="page.pageNum<=1">&lt;</button>
             <button class="active">{{ page.pageNum }}</button>
             <button v-if="page.pageNum + 1 <= totalPages" @click="changePage(page.pageNum + 1)">{{ page.pageNum + 1 }}</button>
             <button v-if="page.pageNum + 2 <= totalPages" @click="changePage(page.pageNum + 2)">{{ page.pageNum + 2 }}</button>
             <button v-if="page.pageNum + 3 <= totalPages" @click="changePage(page.pageNum + 3)">{{ page.pageNum + 3 }}</button>
             <button v-if="page.pageNum + 4 <= totalPages" @click="changePage(page.pageNum + 4)">{{ page.pageNum + 4 }}</button>
             <button @click="changePage(page.pageNum + 1)" :disabled="page.pageNum>=totalPages">&gt;</button>
             <span>{{ page.pageSize }}条/页</span>
           </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { quotationDetailPage, quotationDetail } from '@/api/sale/quotation'

export default {
  name: 'QuotationDetail',
  data() {
    return {
      query: { keyword: '', date: '' },
      page: { pageNum: 1, pageSize: 10 },
      total: 0,
      details: []
    }
  },
  computed: {
    allSelected: {
      get() {
        return this.details.length > 0 && this.details.every(item => item.selected);
      },
      set(value) {
        this.details.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      if (!this.total || !this.page.pageSize) return 1
      return Math.max(1, Math.ceil(this.total / this.page.pageSize))
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const quotationId = this.$route?.query?.quotationId
      const body = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        quotationId: quotationId || undefined,
        productName: this.query.keyword || undefined
      }
      const res = await quotationDetailPage(body)
      const payload = res?.data || res
      const data = payload?.data || {}
      const records = data?.records || []
      this.total = data?.total || 0
      // 先按可用字段映射（兼容不同命名风格）
      const normalized = records.map(r => {
        const qNo = r.quotationNo || r.quotation_no
        const qId = r.quotationId || r.quotation_id || r.quotationID || r.qId
        return { raw: r, qNo, qId }
      })

      this.details = normalized.map(n => ({
        selected: false,
        quoteNumber: n.qNo || n.qId || '-',
        quoteDate: n.raw.quotationDate || n.raw.quotation_date || '-',
        productName: n.raw.productName || n.raw.product_name || '-',
        productCode: n.raw.productCode || n.raw.product_code || '-',
        spec: n.raw.specification || n.raw.spec || n.raw.specification_name || '-',
        category: n.raw.category || n.raw.category_name || '-',
        unit: n.raw.unitName || n.raw.unit || n.raw.unit_name || '-',
        quantity: n.raw.quantity || n.raw.qty || 0,
        unitPrice: n.raw.unitPrice || n.raw.price || n.raw.unit_price || 0,
        lineAmount: n.raw.finalPrice || n.raw.amount || n.raw.total_amount || 0,
        salesPerson: n.raw.salesPersonName || n.raw.sales_person_name || '-',
        remark: n.raw.remark || n.raw.note || '-'
      }))

      // 根据 quotationId 批量补充/校正报价单号（无论分页是否返回了报价单号，都以详情为准）
      const allIds = normalized.filter(n => n.qId).map(n => n.qId)
      const uniqueIds = Array.from(new Set(allIds))
      if (uniqueIds.length) {
        const results = await Promise.all(uniqueIds.map(id => quotationDetail(id).then(r => r?.data || r).catch(() => null)))
        const idToNo = {}
        results.forEach((p, idx) => {
          if (p && (p.code === 200 || p.success === true) && p.data) {
            idToNo[uniqueIds[idx]] = p.data.quotationNo
          }
        })
        this.details = this.details.map((row, i) => {
          const qId = normalized[i]?.qId
          if (qId && idToNo[qId]) {
            return { ...row, quoteNumber: idToNo[qId] }
          }
          return row
        })
      }
    },
    onSearch() {
      this.page.pageNum = 1
      this.fetch()
    },
    onReset() {
      this.query = { keyword: '', date: '' }
      this.page.pageNum = 1
      this.fetch()
    },
    changePage(p) {
      if (p < 1 || p > this.totalPages) return
      this.page.pageNum = p
      this.fetch()
    }
  }
}
</script>

<style scoped>
.quotation-detail { background-color: #f7f8fa; padding: 20px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-header h2 { font-size: 20px; color: #333; }
.header-actions { display: flex; align-items: center; gap: 20px; }
.action-icon { font-size: 18px; color: #666; cursor: pointer; position: relative; }
.icon-bell sup { position: absolute; top: -5px; right: -10px; background: red; color: white; border-radius: 50%; padding: 2px 5px; font-size: 10px; }
.content-area { background: white; padding: 20px; border-radius: 8px; }
.controls-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; margin-bottom: 20px; gap: 15px; }
.btn { border: 1px solid #dcdfe6; background: white; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
.filters { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
.filter-item { display: flex; align-items: center; gap: 5px; }
.filter-item label { color: #666; font-size: 14px; }
.filter-item input { border: 1px solid #dcdfe6; padding: 8px; border-radius: 4px; width: 240px; }
.actions { display: flex; gap: 10px; }
.btn-search { background: #409eff; color: white; border-color: #409eff; }
.table-container { border: 1px solid #ebeef5; border-radius: 4px; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th, .data-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #ebeef5; }
.data-table th { background: #fafafa; color: #606266; font-weight: 500; }
.data-table td { color: #606266; }
.quote-number, .product-name { color: #409eff; cursor: pointer; }
.product-name .product-code { color: #909399; margin-left: 5px; }
.table-footer { display: flex; justify-content: space-between; align-items: center; padding: 15px; }
.footer-actions { display: flex; align-items: center; gap: 10px; }
.btn-export { border: 1px solid #dcdfe6; background: white; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
.pagination { display: flex; align-items: center; gap: 5px; }
.pagination button { border: 1px solid #dcdfe6; background: white; padding: 5px 10px; cursor: pointer; }
.pagination button.active { background: #409eff; color: white; border-color: #409eff; }
</style>
